package com.demo.phone.outbound.service;
import com.alibaba.fastjson.JSON;
import com.demo.phone.outbound.config.OutBoundConfig;
import com.demo.phone.outbound.req.BaseRequest;
import com.demo.phone.outbound.res.BaseRespons;
import com.demo.phone.utils.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * @author : YU.TAN
 * @date : 2021/10/29 10:38
 */
@Component
public class SmartOutboundService {

    @Autowired
    private OutBoundConfig outBoundConfig;

    /**
     * 准备参数
     */
    BaseRequest prepareParameters(Object object) {
        long time = System.currentTimeMillis() / 1000;

        BaseRequest baseRequest = new BaseRequest();
        baseRequest.setAppKey(outBoundConfig.getAppKey());
        baseRequest.setTimeStamp(String.valueOf(time));
        baseRequest.setBrandName("ora");

        if (object != null) {
            HashMap<String, Object> map = new HashMap<>(16);
            map.put("param", object);
            String data = JSON.toJSONString(map);
            baseRequest.setData(data);
        }

        return baseRequest;
    }

    /**
     * 获取签名
     */
    String getSign(Object object, BaseRequest baseRequest) {
        String param = null;
        if (object != null) {
            param = JSON.toJSONString(object);
        }
        String result = "%sappKey=%sparam=%stimestamp=%s%s";
        return String.format(result, outBoundConfig.getAppSecret(), outBoundConfig.getAppKey(), param, baseRequest.getTimeStamp(), outBoundConfig.getAppSecret());
    }

    /**
     * @param object
     * @param url
     * @return
     */
    public BaseRespons handlerTempPlate(Object object, String url) {
        BaseRespons baseRespons = new BaseRespons();
        BaseRequest baseRequest = prepareParameters(object);
        String sign = getSign(object, baseRequest);
        baseRequest.setSign(sign);
        try {
            String data = JSON.toJSONString(baseRequest);
            String result = HttpUtil.sendPost(data, url);
            baseRespons = JSON.parseObject(result, BaseRespons.class);
            return baseRespons;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return baseRespons;
    }

    /**
     * @param url
     * @return
     */
    public BaseRespons handlerTempPlate(String url) {
        return handlerTempPlate(null, url);
    }


}
